import { _decorator, CCInteger, Component, instantiate, Node, Prefab, resources, Sprite, SpriteFrame, UITransform } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('SetNum')
export class SetNum extends Component {
    @property({type: Prefab,})
    numPre: Prefab = null;
    @property(SpriteFrame)
    sprites: SpriteFrame[] = [];
    width: number = 40;
    @property(Number)
    num:number = 5;

    protected start(): void {
        //获取所有数字精灵
        this.setNum(this.num);
    }

    setNum(num: number) {
        //清空之前的数字
        this.node.removeAllChildren();
        //根据传入的数字，实例化对应的数字Prefab，并布局到节点上
        const len = num.toString().length;//获取当前数字位数
        const width = this.width / len;
        //创建各个数字
        for (let i = 0; i < len; i++) {
            const node = instantiate(this.numPre);
            node.parent = this.node;
            const sprite = node.getComponent(Sprite);
            //根据每一位数字，设置对应的图片
            const index = Number(num.toString()[i]);
            sprite.spriteFrame = this.sprites[index];
            //根据宽度和数字位数，设置每个数字的位置,保持居中对齐
            node.setPosition(i * width - (len - 1) * width / 2, 0, 0);
        }
    }





}

